package com.newly.driver.sdk.device.video.service.impl.qiniu;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.newly.driver.sdk.device.video.cloud.channel.QueryChannelReq;
import com.newly.driver.sdk.device.video.cloud.channel.QueryChannelResp;
import com.newly.driver.sdk.device.video.cloud.device.QueryDeviceResp;
import com.newly.driver.sdk.device.video.constants.DeviceConstant;
import com.newly.driver.sdk.device.video.exception.NewlyDeviceException;
import com.newly.driver.sdk.device.video.service.api.IChannel;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author gjm guan
 * @date 2021/10/20 16:21
 * @desc 七牛云
 */
public class QiNiuChannel extends AbstractQiNiuCloud implements IChannel {

    @Autowired
    private QiNiuDevice qiNiuDevice;

    @Override
    public QueryChannelResp listChannel(QueryChannelReq queryChannelReq) {
        try {
            Assert.notNull(queryChannelReq, "查询通道参数异常");
            Assert.notBlank(queryChannelReq.getDeviceId(), "deviceId不能为空");
        } catch (IllegalArgumentException e) {
            throw new NewlyDeviceException(e.getMessage());
        }

        // 如果是被是ipc通道数据也是它本身
        QueryDeviceResp queryDeviceResp = qiNiuDevice.queryDevice(queryChannelReq.getDeviceId());
        if (!ObjectUtil.isEmpty(queryDeviceResp)){
            QueryDeviceResp.Payload payload = queryDeviceResp.getPayloads().get(0);
            int deviceType = payload.getDeviceType();
            if (deviceType == DeviceConstant.DeviceType.IPC.getKey()){
                return new QueryChannelResp(payload);
            }
        }

        // 发起查询通道请求
        Response resp = null;
        try {
            resp = this.getDeviceManager().listChannels(this.namespaceId, queryChannelReq.getDeviceId(), "");
        } catch (QiniuException e) {
            throw new NewlyDeviceException("查询云设备通道失败: ", e);
        }
        JSONObject jsonObject = this.parseMap(resp);
        QueryChannelResp queryChannelResp = new QueryChannelResp(jsonObject);

        return queryChannelResp;
    }
}
